package sopt.dev.view;

import java.util.ArrayList;

import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;

public class FragmentController {

	private static FragmentController mInstance;
	
	static {
		mInstance = new FragmentController();
	}
	
	private FragmentController() { fragList = new ArrayList<Fragment>(); };
		
	private final ArrayList<Fragment> fragList;
	private FragmentManager frgManager;

	public static FragmentController getInstance() {
		if(mInstance == null) {
			return mInstance = new FragmentController();
		}
		return mInstance;
	}
		
	public Fragment getFragment(int idx) {
		return fragList.get(idx);
	}
	
	public void addFragment(FragmentInstance fragment) {
		fragList.add(fragment);
	}
	
	public int getFragmentIndex(Fragment fragment) {
		for(int i = 0; i < fragList.size(); ++i) {
			if(fragList.get(i).equals(fragment)) {
				return i;
			}
		}
		return -1;
	}

	public void replaceFragment(int newFragmentIndex, int layout) {

		Fragment newFragment = getFragment(newFragmentIndex);

		// replace fragment
		final FragmentTransaction transaction = frgManager.beginTransaction();

		transaction.replace(layout, newFragment);

		// Commit the transaction
		transaction.commit();

	}

}
